<template>
	<view class="app">
		<load :ready="ready"></load>
		
		<u-navbar back-icon-name="none" :background="background" :gap="false" back-icon-size="30" :border-bottom="false"></u-navbar>
		<view class="head">
			<image src="/static/logo.png" class="logo" mode="widthFix"></image>
		</view>
		<view class="login-form">
			<view class="title">欢迎登录飞虹燃气</view>
			<view class="form-item">
				<text>手机</text>
				<view style="flex: 1;">
					<u-input placeholder="请输入您的账号" v-model="form.mobile" height="110" :custom-style="{
					padding: '0 10px',
				}"></u-input>
				</view>
			</view>

			<view class="form-item">
				<text>验证码</text>
				<view style="flex: 1;">

					<u-input type="number" placeholder="请输入验证码" v-model="form.verify_code" height="110" :custom-style="{
					padding: '0 10px',
				}"></u-input>
				</view>
				<!-- <text @click="verifyFasong">{{verCode.text}}</text> -->
				<view class="getcode" :class="{
				        active: verCode.isDownIng
				    }" @tap="getCode">
					{{ verCode.text }}
				</view>
			</view>

			<view class="arg-wrap">
				<u-checkbox v-model="arg">
					同意<text @click.stop="link(`/pages/index/agreement`)">《用户协议》</text>
				</u-checkbox>
				<view>
					<button class="u-reset-button btn-wx" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
						<u-icon name="phone" color="#0093dd" size="40"></u-icon>
						<text>手机号快捷登录</text>
					</button>
				</view>

			</view>
			<u-button type="primary" shape="circle" :loading="isLoading" @click="submit"
				:custom-style="btnStyle">登录</u-button>

			<!-- <view style="padding: 20rpx 0 0 ;">
				<u-button type="primary" shape="circle" :loading="isLoading" @click="submit" :custom-style="{
				 ...btnStyle,
				background: '#11961e'
				}">手机号授权登录</u-button>
			</view> -->

			<!--  <view class="reg-text" @tap="link('/pages/login/reg')">还没有账号？<text>去注册</text></view> -->
			<view class="tip">没注册的账号会默认注册</view>
		</view>

		<tfgg-verify ref="verifyElement" @result="verifyResult" />

	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations,
		mapGetters
	} from 'vuex';
	import {
		mixinsBase
	} from '@/common/js/mixins';
	import tfggVerify from '@/components/tfgg-verify/tfgg-verify.vue';

	let that;
	export default {
		mixins: [mixinsBase],
		components: {
			"tfgg-verify": tfggVerify
		},
		data() {
			let form = {
				"verify_code": "",
				"mobile": "",
				"code": '',
			}
			let arg = false
			if (this.$config.debug) {
				// form ={
				// 	"verify_code": "999999",
				// 	"mobile": "13580052553",
				// 	"code":'',
				// }
				// arg = true
			}
			return {
				navbar: {},
				ready: true,
				// listTip: null,
				btnStyle: this.$config.btnStyle,
				verCode: {
					text: '获取验证码',
					code: '',
					isDownIng: false,
					i: 60,
					t: null,
				},
				form,
				background: {
					 backgroundColor: 'rgba(0,0,0,0)'
				},
				lineStyle: {
					right: '20rpx',
					bottom: '4px'
				},
				errText: '账号或密码错误，请重新输入',
				isLoading: false,
				arg,
				openid: '',
				session_key: '',
				access_token:'',
			};
		},
		onLoad() {
			that = this;
			this.setUserInfo(null);
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('token')
			// this.getOpenid();
		},
		onShow() {
			// #ifdef H5
			this.$common.h5SetTitle('');
			// #endif
		},
		onUnload() {
			that = null
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {
			// this.getInit(data=>{
			//      uni.stopPullDownRefresh();
			//      common.showTip('刷新成功');
			// });
		},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {
			//       return {
			// 	// path,
			// 	imageUrl:config.shareImg,
			// 	// title
			// }
		},
		methods: {
			async getPhoneNumber(e) {
				
				console.log(e.detail.code) // 动态令牌
				console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
				console.log(e.detail.errno) // 错误码（失败时返回）
				
				if(e.detail.errno)return;
				uni.showLoading();
				
				const res = await this.$api.getWeChatToken();
				if (res.data.code == this.$config.RESOK) {
					this.access_token = res.data.data.access_token;
				}
				let params = {
					code:e.detail.code,
					access_token:this.access_token, 
				}
				console.log('params', params)
				const res2 = await this.$api.getWeChatlphone(params);
				if (res2.data.code == this.$config.RESOK) {
					if(res2.data.data.errcode==0){
						this.mobwxLogin(res2.data.data.phone_info.purePhoneNumber)
					}
				} else{
					this.$message.error(res2.data.msg);
				}
			},
			async getOpenid() {
				let params = {
					appid: this.$config.appid,
					secret: this.$config.sessionKey,
				}
				let [lErr, lRes] = await uni.login();
				if (lRes && lRes.code) {
					params.js_code = lRes.code
				}
				
				console.log(params.js_code)
				// const res = await this.$api.jscode2session(params)
				// console.log('await this.$api.jscode2session结果')
				// console.log(res)
				// if (res.data.openid) {
				// 	this.openid = res.data.openid;
				// 	this.session_key = res.data.session_key;
				// }
				// this.ready = true;
				// const res = await this.$api.getWeChatToken()
				// if (res.code == this.$config.RESOK) {
				// 	this.session_key = res.data.access_token;
				// }
			},
			async mobwxLogin(mobile){
				let res;
				let params = {
					mobile,
					verify_code:888888,
				}
				// #ifdef MP-WEIXIN
				let [lErr, lRes] = await uni.login();
				if (lRes && lRes.code) {
					params.code = lRes.code
				}
				// #endif
				try {
					res = await this.$api.login(params);
				} catch (err) {
					this.$message.error(JSON.stringify(err.errMsg));
					this.isLoading = false;
					return
				}
				res = res.data;
				this.isLoading = false;
					uni.hideLoading();
				if (res.code == this.$config.RESOK) {
					let userInfo = this.$user.normalFilter({
						...res.data,
					});
					this.$message.success('登录成功');
					uni.setStorageSync('token', userInfo.token);
					console.log(JSON.stringify(userInfo));
					this.setUserInfo(userInfo);
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/navbar/index'
						})
					}, this.$config.timeLoad);
				
				} else {
					this.$message.error(res.msg);
				}
			},
			
			async getCode() {
				this.$common.getCode(that, 'regCaptcha');
			},
			/* 校验结果回调函数 */
			verifyResult(res) {
				if (res) {
					this.$refs.verifyElement.reset(); //校验成功重置插件
					console.log('验证成功')
					this.$common.getCode(this, 'regCaptcha');
				}
				console.log(res);
			},
			/* 显示校验弹窗 */
			verifyFasong() {
				if (this.verCode.isDownIng) {
					return false;
				}
				this.$refs.verifyElement.show();
			},
			/* 校验插件重置 */
			verifyReset() {
				this.$refs.verifyElement.reset();
			},
			async submit() {
				if (!this.arg) {
					this.$message.error('同意协议才能登录账号');
					return;
				}
				if (this.isLoading) return;
				if (!this.form.mobile.length) {
					this.$message.error('请输手机号');
					return;
				}
				if (!this.form.verify_code.length) {
					this.$message.error('请输入验证码');
					return;
				}
				this.isLoading = true;
				let params = {
					...this.form
				}
				// #ifdef MP-WEIXIN
				let [lErr, lRes] = await uni.login();
				if (lRes && lRes.code) {
					params.code = lRes.code
				}
				// #endif
				let res;
				try {
					res = await this.$api.login(params);
				} catch (err) {
					this.$message.error(JSON.stringify(err.errMsg));
					this.isLoading = false;
					return
				}
				res = res.data;
				this.isLoading = false;
				if (res.code == this.$config.RESOK) {
					let userInfo = this.$user.normalFilter({
						...res.data,
					});
					this.$message.success('登录成功');
					uni.setStorageSync('token', userInfo.token);
					console.log(JSON.stringify(userInfo));
					this.setUserInfo(userInfo);
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/navbar/index'
						})
						// if(userInfo.reg_time && userInfo.reg_time.length){
						// 	uni.switchTab({
						// 		url: '/pages/navbar/user'
						// 	})
						// } else{
						// 	uni.redirectTo({
						// 		url: `/pages/login/reg?mobile=${params.mobile}`
						// 	})
						// }
					}, this.$config.timeLoad);

				} else {
					this.$message.error(res.msg);
				}
			},
			...mapActions(['setUserInfo']),
		},
		computed: {
			getBtnStyle() {
				let style = {};
				if (this.verCode.isDownIng) {
					style = Object.assign({}, this.$config.btnStyle3, {
						height: '80rpx',
						lineHeight: '80rpx',
						fontSize: '13px',
						width: '30%'
					})
				} else {
					style = Object.assign({}, this.$config.btnStyle2, {
						height: '80rpx',
						lineHeight: '80rpx',
						fontSize: '13px',
						width: '30%'
					})
				}
				return style;
			},
			...mapState({
				userInfo: 'userInfo',
			})
		},
	};
</script>

<style lang="scss">
	page {
		background: $color;
	}
</style>
<style scoped lang="scss">
	@import '@/common/css/login.scss';

	.head {
		background: $color;
		text-align: center;
		padding: 40rpx 0;

		.logo {
			width: 400rpx;

		}
	}

	.arg-wrap {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 13px;
		margin-bottom: 40rpx;
		padding: 30rpx 0;

		text {
			color: $color;
		}

		.btn-wx {
			color: #333;
			display: flex;
			align-items: center;

			text {
				margin-left: 5px;
				color: #0093dd;
				font-size: 15px;
			}
		}
	}

	.login-form {
		background: #fff;
		margin: 0 20rpx;
		padding: 40rpx 30rpx;
		border-radius: 5px;
	}

	.title {
		font-size: 20px;
		font-weight: bold;
	}

	.tip {
		text-align: center;
		color: #666;
		padding: 3px 0;
		font-size: 13px;
	}
</style>